#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-10-16 15:46:00
# @Author  : xycfree
# @Link    : http://example.org
# @Version : $Id$

import os
import uuid
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from flask import render_template, Flask, jsonify, url_for, request, session, redirect
from modules import user, db, conf, message, monitor, cmdb, remote, upload
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.secret_key = 'x\xa2\xe3e\xca\xd57\x96[\xa7\xb7(KRr\xe5\xa7\x0c\x87\x82\xb9\x9e2\x82'
app.config['UPLOAD_FOLDER'] = conf._UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = conf._MAX_CONTENT_LENGTH  # 16M，允许最大上传文件


# 主页
@app.route('/')
def index():
    return render_template('index.html')


# 登录
@app.route('/user/login', methods=['POST', 'GET'])
def login():
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        if user_info['phone'] and user_info['passwd']:
            u = user.User(**user_info)
            result = u.login()
            if result['code'] == 0000:
                session['phone'] = user_info['phone']
                return redirect(url_for('index'))
            # else:

            # result = {
            #     'code': 1005,
            #     'message': conf._code.get(1005, '登录失败')
            # }
        else:
            result = {
                'code': 1004,
                'message': conf._code.get(1004, '用户名或密码不能为空')
            }

    return render_template('login.html', result=result)


# 注册
@app.route('/user/register', methods=['POST', 'GET'])
def register():
    result = {}
    if request.method == 'POST':
        reg_info = request.form.to_dict()
        u = user.User(reg_info=reg_info)
        result = u.register()
        if result.get('code') == 0000:
            return redirect(url_for('index'))
    return render_template('reg.html', result=result)


# 短信使用情况
@app.route('/message/usage')
def message_usage():
    result = {}
    m = message.Message()
    result = m.query_mess()

    return render_template('message_usage.html', result=result)


# 短信日志
@app.route('/message/log')
def message_log():
    m = message.Message()
    result = m.log_info('message_log')
    return render_template('message_log.html', result=result)


# 发送短信
@app.route('/message/send', methods=['POST', 'GET'])
def message_send():
    result = {}
    if request.method == 'POST':
        mes_info = request.form.to_dict()
        m = message.Message()
        result = m.mess_send(**mes_info)
    return render_template('message_send.html', result=result)


# 上课通知
@app.route('/message/notify', methods=['POST', 'GET'])
def message_notify():
    result = {}
    if request.method == 'POST':
        mes_info = request.form.to_dict()
        m = message.Message()
        result = m.notify(**mes_info)
    return render_template('message_notify.html', result=result)


# 用户信息 激活
@app.route('/user/info', methods=['POST', 'GET'])
def user_info():
    u = user.User()
    if request.method == 'POST':
        phone = request.form['phone']
        result = u.status_on(phone=phone)
        return redirect(url_for('user_info'))

    result = u.user_info()
    return render_template('user_info.html', result=result)


# 用户信息修改
@app.route('/user/edit', methods=['POST', 'GET'])
def user_edit():
    u = user.User()
    phone = session.get('phone')
    code = message = ''
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        result = u.user_edit(user_info=user_info)
        code, message = result['code'], result['message']
        print code, message

    # if result.get('code') == 0000:
    #     return redirect(url_for('user_edit'))
    # else:
    #     code,message = result['code'],result['message']

    result = u.info(session.get('phone'))

    return render_template('user_edit.html', result=result, code=code, message=message)


# 主机详情api信息
@app.route('/api/monitor')
def api_monitor():
    m = monitor.Monitor()
    result = m.get_all_info()
    return jsonify(result)


# 主机详情信息
@app.route('/monitor')
def view_monitor():
    return render_template('monitor.html')


@app.route('/cmdb/<action>', methods=['GET', 'POST'])
@app.route('/cmdb/<action>/<asset>', methods=['GET', 'POST'])
def cmdb_add(action='list', asset='host'):
    actions = ['add', 'edit', 'del', 'list']
    assets = ['room', 'cabinet', 'host']
    if request.method == 'GET':
        if action == actions[0]:
            return render_template('cmdbadd.html')
        elif action == actions[1]:
            return render_template('cmdbedit.html')
        else:
            c = cmdb.Cmdb()
            if asset == assets[0]:  # room
                result = c.room_list()
                return render_template('cmdb_room_list.html', result=result)
            elif asset == assets[1]:  # cabinet
                result = c.cabinet_list()
                return render_template('cmdb_cabinet_list.html', result=result)
            else:
                result = c.host_list()
                return render_template('cmdb_host_list.html', result=result)
    elif request.method == 'POST':
        c = cmdb.Cmdb()
        info = request.form.to_dict()
        if action == actions[0]:  # add增加
            if asset == assets[0]:  # room机房
                result = c.room_add(**info)
            elif asset == assets[1]:  # add/cabinet机柜
                result = c.cabinet_add(**info)
            else:
                result = c.host_add(**info)  # add/host
        elif action == actions[1]:  # edit修改
            if asset == assets[0]:  # /edit/room机房
                result = c.room_edit(**info)
            elif asset == assets[1]:  # /edit/cabinet机柜
                result = c.cabinet_edit(**info)
            else:
                result = c.host_edit(**info)  # /edit/host
        elif action == actions[2]:  # del删除
            if asset == assets[0]:  # /del/room机房
                result = c.room_del(**info)
                return redirect('/cmdb/list/room')
            elif asset == assets[1]:  # /del/cabinet机柜
                result = c.cabinet_del(**info)
                return redirect('/cmdb/list/cabinet')
            else:
                result = c.host_del(**info)  # /del/host
                return redirect('/cmdb/list/host')
        else:
            result = {'code': 2013,
                      'message': conf._code.get(2013, '请提交正确的URL')}
        return jsonify(result)
    else:
        return jsonify({
            'code': 2014,
            'message': conf._code.get(2014, '服务器不支持get/post以外的请求')
        })


# 执行远程命令
@app.route('/ops/remote', methods=['POST', 'GET'])
def ops_remote():
    r = remote.Remote()
    result = r.get_hosts()
    if request.method == 'POST':
        info = request.form.to_dict()
        result = r.run(**info)
        return jsonify(result)
    return render_template('remote.html', result=result)


# 文件上传
@app.route('/ops/upload', methods=['POST', 'GET'])
def ops_upload():
    r = remote.Remote()
    result = r.get_hosts()
    if request.method == 'POST':
        u = upload.Upload()
        info = request.form.to_dict()
        res = u.load_path(info['ip'])  # 创建远程服务器上传文件目录
        if res['code'] in (0000, 2016):  # 创建成功，已创建

            file = request.files['file']  # 获取上传的文件
            filename = secure_filename(file.filename)  # 获取上传文件的文件名
            uuid_name = str(uuid.uuid4())
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) #文件保存到本地
            file.save(os.path.join(conf._UPLOAD_FOLDER, filename))  # 文件保存到本地
            localpath = os.path.abspath(conf._UPLOAD_FOLDER)  # 本地文件路径+文件
            remotepath = conf._REMOTE_FOLDER  # 远程文件夹+文件名
            # remotepath = conf._REMOTE_FOLDER + filename
            result = u.upload_file(info['ip'], localpath, remotepath, filename)  # 本地文件上传到服务器
            os.remove(os.path.join(conf._UPLOAD_FOLDER, filename))  # 删除本地临时保存的文件

            # 插入数据库文件信息
            if u.insert_file(filename, uuid_name, remotepath) == 1:
                print '插入成功'
            else:
                print '插入失败'

            return render_template('upload_file.html', resu=result)
        else:
            # 远程服务器路径不存在或创建失败
            return render_template('upload_file.html', resu=res)
            pass

    return render_template('upload.html', result=result)


# 退出
@app.route('/user/logout', methods=['POST', 'GET'])
def logout():
    # 如果会话中有用户名就删除它。
    session.pop('phone', None)
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000, debug=True)
